package com.eling.elcms.system.dao.hibernate;

import com.eling.elcms.core.dao.hibernate.GenericDaoHibernate;
import com.eling.elcms.privilege.model.Role;
import com.eling.elcms.system.dao.IElcmsUserDao;
import com.eling.elcms.system.model.ElcmsUser;
import org.springframework.stereotype.Repository;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

@Repository
public class ElcmsUserDaoHibernate extends GenericDaoHibernate<ElcmsUser, Long> implements IElcmsUserDao {

	public ElcmsUserDaoHibernate() {
		super(ElcmsUser.class);
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<ElcmsUser> queryUsersByBuilding(Long pkBuilding, Long pkRole) {
		// 只查询不具备1、2、7角色pk的用户，HQL暂时没找到好的写法，先用Java过滤，后续再优化。
		List<ElcmsUser> users = new ArrayList<ElcmsUser>();
		String hql = "select distinct u from User u join u.roles r join u.buildings b where r.pkRole not in (1,2) and b.pkBuilding=:pkBuilding and r.pkRole=:pkRole";
		users.addAll(getSession().createQuery(hql).setParameter("pkBuilding", pkBuilding).setParameter("pkRole", pkRole).list());
	
		for (Iterator<ElcmsUser> it = users.iterator(); it.hasNext();) {
			ElcmsUser user = it.next();
			for (Role role : user.getRoles()) {
				int pkR = role.getPkRole().intValue();
				if ( pkR == 1 || pkR ==2 || pkR == 7) {
					it.remove();
					break;
				}
			}
		}
		return users;
	}

}
